package ca.venasse.pinventory.client;

import java.util.Map;

import org.axonframework.commandhandling.CommandBus;
import org.axonframework.domain.UUIDAggregateIdentifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;

import ca.venasse.pinventory.common.Category;
import ca.venasse.pinventory.common.Name;
import ca.venasse.pinventory.part.command.CreatePartCommand;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;

@org.springframework.stereotype.Component("mainController")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MainController extends GenericForwardComposer {

	public static final String BUTTON_PROCESS = "process";
	public static final String FIELD_NAME = "name";

	private static final long serialVersionUID = 1L;

	private static final Table<Boolean, String, String> VIEW_STATUSES;

	static {
		VIEW_STATUSES = HashBasedTable.create();

		VIEW_STATUSES.put(false, String.format("%s-readonly", FIELD_NAME), "false");
		VIEW_STATUSES.put(false, String.format("%s-disabled", BUTTON_PROCESS), "false");

		VIEW_STATUSES.put(true, String.format("%s-readonly", FIELD_NAME), "true");
		VIEW_STATUSES.put(true, String.format("%s-disabled", BUTTON_PROCESS), "true");
	}

	private AnnotateDataBinder binder;

	@Autowired
	private CommandBus commandBus;

	private Name name;

	private boolean readOnlyEditor;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);

		this.readOnlyEditor = false;
		System.out.println(Boolean.valueOf(this.readOnlyEditor).toString());

		this.binder = new AnnotateDataBinder(comp);
		this.binder.bindBean("controller", this);
		this.binder.loadAll();
	}

	public Name getName() {
		return this.name;
	}

	public Map<String, String> getStatusFor() {
		Map<String, String> row = VIEW_STATUSES.row(this.readOnlyEditor);
		return row;
	}

	public boolean isReadOnlyEditor() {
		return this.readOnlyEditor;
	}

	public void onChangeStatus(ForwardEvent forwardEvent) {
		this.binder.loadAll();
	}

	public void onProcess() {
		this.binder.saveAll();
		CreatePartCommand command = new CreatePartCommand(
			new UUIDAggregateIdentifier(),
			this.name,
			Category.create("Category"));
		this.commandBus.dispatch(command);
		System.out.println("Processing...");
		System.out.println(this.name.asString());
	}

	public void setName(Name name) {
		this.name = name;
	}

	public void setReadOnlyEditor(boolean readOnlyEditor) {
		this.readOnlyEditor = readOnlyEditor;
	}

}
